using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace WindowsGame5 {
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Model terrain;
        HeightMapInfo heightMap;

        Vector3 cameraPosition;
        Vector3 cameraDirection;
        Vector3 walkDirection;
        Vector3 cameraPositionOffset;
        Vector3 cameraUp;
        Vector3 cameraRight;
        Vector3 cameraVelocity;
        float thrustSpeed;
        float gravityAcceleration;
        float soarSpeed;
        float initialJumpSpeed;
        float rotationFactor;
        bool jumping;

        BoundingBox worldBound;
        Missile[] missiles;
        float missilePower = 400.0f;
        float missileScale = 3.0f;
        int missileCounts = 20;

        Matrix projection;
        Matrix view;

        Vector2 mousePosition;
        bool mouseLeftPressed;

        ParticleSystem explosionParticles;
        ParticleSystem projectileTrailParticles;

        public Game1() {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            Content.RootDirectory = "Content";
            explosionParticles = new ExplosionParticleSystem(this, Content);
            projectileTrailParticles = new ProjectileTrailParticleSystem(this, Content);
            projectileTrailParticles.DrawOrder = 300;
            explosionParticles.DrawOrder = 400;
            Components.Add(explosionParticles);
            Components.Add(projectileTrailParticles);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize() {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent() {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            terrain = Content.Load<Model>("terrain");
            heightMap = terrain.Tag as HeightMapInfo;
            if (heightMap == null) {
                throw new InvalidOperationException();
            }
            worldBound = heightMap.Bound;
            worldBound.Max.Y += 1000.0f;

            missiles = new Missile[missileCounts];
            for (int i = 0; i < missiles.Length; i++)
                missiles[i] = new Missile(Content.Load<Model>("missile"), missileScale, 
                    projectileTrailParticles, explosionParticles);

            projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4, graphics.GraphicsDevice.Viewport.AspectRatio,
                1, 10000);

            cameraPosition = Vector3.Zero;
            cameraDirection = Vector3.Forward;
            cameraUp = Vector3.Up;
            cameraPositionOffset = new Vector3(0.0f, 30.0f, 0.0f);
            cameraVelocity = Vector3.Zero;

            thrustSpeed = 150.0f;
            gravityAcceleration = 1000.0f;
            soarSpeed = 0.0f;
            initialJumpSpeed = 300.0f;
            rotationFactor = 0.004f;
            jumping = false;

            
            Mouse.SetPosition(
                graphics.PreferredBackBufferWidth / 2, 
                graphics.PreferredBackBufferHeight / 2);
            MouseState mouse = Mouse.GetState();
            mousePosition = new Vector2(mouse.X, mouse.Y);
            mouseLeftPressed = false;
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent() {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime) {
            float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            if (IsActive) {
                UpdateCamera(elapsedTime);
            }
            UpdateMissiles(elapsedTime);

            base.Update(gameTime);
        }

        public void UpdateMissiles(float elapsedTime) {
            MouseState mouse = Mouse.GetState();
            if (mouseLeftPressed == false && mouse.LeftButton == ButtonState.Pressed) {
                mouseLeftPressed = true;
                FireMissile();
            } else if (mouseLeftPressed == true && mouse.LeftButton == ButtonState.Released) {
                mouseLeftPressed = false;
            }

            foreach (Missile missile in missiles) {
                if (missile.Active == true) {
                    missile.Update(elapsedTime, worldBound, heightMap);
                }
            }
        }
        public void FireMissile() {
            foreach (Missile missile in missiles) {
                if (missile.Active == true)
                    continue;
                missile.activate(cameraPosition, cameraDirection, missilePower);
                return;
            }
        }
        public void UpdateCamera(float elapsedTime) {
            cameraRight = Vector3.Cross(cameraDirection, cameraUp);

            updateCameraDirection(elapsedTime);
            updateCameraPosition(elapsedTime);

            view = Matrix.CreateLookAt(cameraPosition, cameraPosition + cameraDirection, cameraUp);
        }
        public void updateCameraPosition(float elapsedTime) {
            KeyboardState keyboard = Keyboard.GetState();
            Vector2 thrustAmount = Vector2.Zero;
            if (keyboard.IsKeyDown(Keys.W)) {
                thrustAmount.Y = 1.0f;
            } else if (keyboard.IsKeyDown(Keys.S)) {
                thrustAmount.Y = -1.0f;
            }
            if (keyboard.IsKeyDown(Keys.A)) {
                thrustAmount.X = -1.0f;
                thrustAmount.Normalize();
            } else if (keyboard.IsKeyDown(Keys.D)) {
                thrustAmount.X = 1.0f;
                thrustAmount.Normalize();
            }
            if (!jumping && keyboard.IsKeyDown(Keys.Space)) {
                jumping = true;
                soarSpeed = initialJumpSpeed;
            }

            cameraVelocity =
                (walkDirection * thrustAmount.Y + cameraRight * thrustAmount.X)
                * thrustSpeed;
            cameraPosition += cameraVelocity * elapsedTime;

            if (heightMap.IsOnHeightmap(cameraPosition)) {
                float minimumHeight =
                    heightMap.GetHeight(cameraPosition) + cameraPositionOffset.Y;

                soarSpeed -= gravityAcceleration * elapsedTime;
                cameraPosition.Y += soarSpeed * elapsedTime;

                if (cameraPosition.Y < minimumHeight) {
                    cameraPosition.Y = minimumHeight;
                    jumping = false;
                    soarSpeed = 0.0f;
                }
            }
        }
        public void updateCameraDirection(float elapsedTime) {
            MouseState mouse = Mouse.GetState();
            Vector2 movedMousePosition = new Vector2(mouse.X, mouse.Y);
            Vector2 rotationAmount = movedMousePosition - mousePosition;
            rotationAmount *= rotationFactor;

            Matrix rotationMatrix =
                Matrix.CreateFromAxisAngle(cameraRight, -rotationAmount.Y)
                * Matrix.CreateRotationY(-rotationAmount.X);
            Vector3 tiltedDirection =
                Vector3.TransformNormal(cameraDirection, rotationMatrix);
            tiltedDirection.Normalize();

            Mouse.SetPosition((int)mousePosition.X, (int)mousePosition.Y);
            cameraDirection = tiltedDirection;
            walkDirection = new Vector3(cameraDirection.X, 0, cameraDirection.Z);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime) {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            TextureAddressMode sample0u = graphics.GraphicsDevice.SamplerStates[0].AddressU;
            TextureAddressMode sample0v = graphics.GraphicsDevice.SamplerStates[0].AddressV;

            GraphicsDevice.RenderState.DepthBufferEnable = true;
            GraphicsDevice.RenderState.AlphaBlendEnable = false;
            GraphicsDevice.RenderState.AlphaTestEnable = false;
            DrawModel(terrain, Matrix.Identity);
            foreach (Missile missile in missiles) {
                if (missile.Active == false)
                    continue;
                DrawModel(missile.Model, missile.getTransformation());
            }

            projectileTrailParticles.SetCamera(view, projection);
            explosionParticles.SetCamera(view, projection);

            base.Draw(gameTime);

            graphics.GraphicsDevice.SamplerStates[0].AddressU = sample0u;
            graphics.GraphicsDevice.SamplerStates[0].AddressV = sample0v;
        }
        public void DrawModel(Model model, Matrix world) {
            Matrix[] boneTransforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(boneTransforms);

            foreach (ModelMesh mesh in model.Meshes) {
                foreach (BasicEffect effect in mesh.Effects) {
                    effect.World = world;
                    effect.View = view;
                    effect.Projection = projection;

                    effect.EnableDefaultLighting();
                    effect.PreferPerPixelLighting = true;

                    // Set the fog to match the distant mountains
                    // that are drawn into the sky texture.
                    effect.FogEnabled = true;
                    effect.FogColor = Color.CornflowerBlue.ToVector3();
                    effect.FogStart = 1000;
                    effect.FogEnd = 3200;
                }

                mesh.Draw();
            }
        }
    }
}
